package com.sale.salesystem.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sale.salesystem.dto.DetailQueryDTO;
import com.sale.salesystem.entity.ReportData;
import com.sale.salesystem.exception.BusinessException;
import com.sale.salesystem.service.AnalysisService;
import com.sale.salesystem.service.PermissionService;
import com.sale.salesystem.vo.DashboardVO;
import com.sale.salesystem.vo.ResultVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/analysis")
@RequiredArgsConstructor
@Slf4j
public class AnalysisController {

    private final AnalysisService analysisService;
    private final PermissionService permissionService;

    @GetMapping("/{type}")
    public ResultVO<DashboardVO> getDashboardData(
        @PathVariable String type,
        @RequestParam Long userId
    ) {
        // 检查用户是否有权限访问该仪表板
        if (!permissionService.hasPermission(userId, type)) {
            throw new BusinessException("请联系管理员获取权限");
        }
        
        // 获取仪表板数据
        DashboardVO data = analysisService.getDashboardData(type);
        data.setHasPermission(true);  // 设置权限标记
        return ResultVO.success(data);
    }

    @GetMapping("/{type}/check")
    public ResultVO<Boolean> checkPermission(
        @PathVariable String type,
        @RequestParam Long userId
    ) {
        return ResultVO.success(permissionService.hasPermission(userId, type));
    }

    @PostMapping("/all")
    public ResultVO<IPage<ReportData>> getAllData(@RequestBody DetailQueryDTO queryDTO) {
        log.info("queryDTO: {}", queryDTO);
        // 检查用户是否有权限访问该仪表板
        if (!permissionService.hasPermission(queryDTO.getUserId(), "detail")) {
            throw new BusinessException("请联系管理员获取权限");
        }
        
        // 获取所有数据
        return ResultVO.success(analysisService.getAllData(queryDTO));
    }
} 